import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:yuellyfactory/util/ToastUtil.dart';
import 'package:yuellyfactory/views/dto/PriceMaterial.dart';

import '../../eventbus/EventBusUtil.dart';
import '../../eventbus/EventRefreshPart.dart';
import '../../util/BaseRequest.dart';
import '../../util/ColorUtil.dart';
import '../../util/DialogUtil.dart';
import '../../util/ViewUtil.dart';
import '../dto/PriceParm.dart';
import '../dto/PricePart.dart';
import '../dto/PriceRule.dart';

class MaterialChildListEditVC extends StatefulWidget {

  final PricePart priceModel;
  final PricePart pricePart;
  final PriceMaterial priceMaterial;

  final VoidCallback callback;
  const MaterialChildListEditVC({super.key, required this.pricePart, required this.callback, required this.priceMaterial, required this.priceModel});

  @override
  State<MaterialChildListEditVC> createState() => _MaterialChildListEditVCState();
}

class _MaterialChildListEditVCState extends State<MaterialChildListEditVC> {
  
  Map<String,dynamic> values={};
  final dialogKey = GlobalKey<ShadFormState>();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    if(widget.priceMaterial.data.isNotEmpty){
      List<dynamic> list = json.decode(widget.priceMaterial.data);
      for(var item in list){
        var id=item["id"];
        var value=item["value"];
        var rule=item["rule"];
        var handle=item["handle"];
        debugPrint("$id===$value");
        if(rule!=null&&rule.toString().contains("[")){
          values[id]=rule;
        }else{
          if(handle==0){
            values[id]=value;
          }

        }
      }
    }
  }
  @override
  Widget build(BuildContext context) {
    return ShadSheet(
      onClosing: (){
        widget.callback();
      },
      constraints: const BoxConstraints(minWidth: 800,maxWidth: 800),
      title: const  Text("零件编辑"),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Wrap(
            crossAxisAlignment: WrapCrossAlignment.start,
            runAlignment: WrapAlignment.start,
            direction: Axis.horizontal, // 水平方向排列（默认）
            alignment: WrapAlignment.start, // 水平靠左（默认值，可省略）
            spacing: 10, // 子组件横向间距
            runSpacing: 0, // 换行后纵向间距
            children: paramView(),
          ),

          const SizedBox(height: 16),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [ViewUtil.textButton('保存', ViewUtil.screenWidth(400), ViewUtil.screenHeight(30), ViewUtil.radio(15),
                ColorUtil.colorBlue, ColorUtil.colorBlue, Colors.white , ViewUtil.fontSize(25), (){
                  save();
                }),],
          ),
        ],
      ),

    );
  }

  List<Widget> paramView(){
    List<Widget> widgets=[];
    for(PriceParm parm in widget.pricePart.childParmList){
      widgets.add(SizedBox(width: 230,
        child:
        ShadInput(
          prefix: Text(parm.name),
          suffix: Text(parm.unit??""),
          textAlign: TextAlign.end,
          placeholder: Text("请输入${parm.name}"),
          enabled: parm.handle==0,
          initialValue: parm.handle==0? getParmValue(parm.id):getRuleString(values.containsKey(parm.id)?values[parm.id]:parm.rule),
          onChanged: (value){
            debugPrint(value);
            parm.value=value;
            values[parm.id]=value;
            //updateValue(parm);
          },
        ),));
    }
    return widgets;
  }

  getRuleString(var rule){
    var ruleStr="";
    if(rule.isNotEmpty){
      debugPrint(rule);
      if(rule.toString().contains("[")){
        List<dynamic> list = json.decode(rule);
        for(var item in list){
          PriceRule rule=PriceRule.fromJson(item);
          if(rule.handle==0){
            ruleStr="$ruleStr${rule.value}";
          }else{
            ruleStr="$ruleStr${rule.name}";
          }
        }
      }else{
        return rule;
      }

    }
    return ruleStr;
  }
  
   getParmValue(String id){
    String value="";
    if(values.containsKey(id)){
      value=values[id].toString();
    }
    
    return value;
   }

  void updateValue(PriceParm parm){
    var parms={
      "id":parm.id,
      "value":parm.value
    };

  }

  void save(){
    bool result=true;
    for(PriceParm parm in widget.pricePart.childParmList){
      if(parm.handle==0&&parm.required==1){
        var value=getParmValue(parm.id);
        if(value.toString().isEmpty){
          ToastUtil.showToast("请输入${parm.name}");
          result=false;
          break;
        }
      }
    }
    if(!result){
      return;
    }


    var parm={
      "partId":widget.pricePart.id,
      "id":widget.priceMaterial.id,
      "modelId":widget.priceModel.id,
      "data":values
    };


    BaseRequest.postHttp("price/modelmaterialitemedit",parameters: parm, canTip: true, context: context, onSuccess: (data){

      bool result=BaseRequest.chekResponse(data, true);
      if(result){
        bool canChange=data["data"];
        if(canChange){
          ToastUtil.showToast("编辑成功");
          eventBus.fire(EventRefreshPart());
        }else{
          //有多个相同的型号配置不可以直接修改
          showCopyPartDialog();
          return;
        }

      }
      Navigator.pop(context);
    }, onError: (error){

    });
  }

  void showCopyPartDialog(){
    DialogUtil.showConfimDialog(context, "当前型号在多个机型里面进行了配置，不允许直接修改参数，确定将发起拷贝型号${widget.pricePart.name}全部数据", "", "确定", (){
      Navigator.pop(context);
      showInputPartName();

    });
  }

  void showInputPartName(){
    showShadDialog(context: context, builder: (context)=>
        ShadDialog(
            actions: [ShadButton(child: Text('确定'),onPressed: (){
                submitCopy();
            },)],
            child:
            ShadForm(
              key: dialogKey,
              child: ShadInputFormField(
                id: 'name',
                label: const Text('新型号名称'),
                placeholder: const Text('请输入新型号名称'),
                validator: (v) {
                  if (v.isEmpty) {
                    return '请输入新型号名称';
                  }
                  return null;
                },
              ),)

        )
    );
  }

  void submitCopy(){
    if (dialogKey.currentState!.saveAndValidate()) {
      var values = dialogKey.currentState!.value;
      var name = values["name"];
      var parm={
        "name":name,
        "id":widget.pricePart.id,
        "modelId":widget.pricePart.modelId,
      };
      BaseRequest.postHttp("price/modelpartcopy",parameters: parm, canTip: true, context: context, onSuccess: (data){
        bool result=BaseRequest.chekResponse(data, true);
        if(result){
          ToastUtil.showToast("拷贝成功");
          eventBus.fire(EventRefreshPart());
          Navigator.pop(context);
          Navigator.pop(context);
        }
      }, onError: (error){

      });


    }
  }
}
